package com.tledu.spring.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tledu.spring.core.entity.AjaxResult;
import com.tledu.spring.domain.MaterialInfo;
import com.tledu.spring.domain.User;
import com.tledu.spring.service.IUserService;
import lombok.AllArgsConstructor;
import org.apache.tomcat.util.http.fileupload.util.LimitedInputStream;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.thymeleaf.IEngineConfiguration;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author rupert-tears
 * @since 2021-07-08
 */
@Controller
@RequestMapping("/spring/user")
@AllArgsConstructor
public class UserController {
    /**
     * 注入服务实体
     */
    private final IUserService userService;

    @RequestMapping("show")
    public String userJump(){
        return "user/show";
    }

    @PostMapping("showInfo")
    @ResponseBody
    public AjaxResult<PageInfo<User>> show(Integer page, Integer limit){
        // 设置前端传来的 分页信息
        PageHelper.startPage(page,limit);
        // 获取数据库展示信息
        List<User> users = userService.show();
        // 封装到分页插件中
        PageInfo<User> pageInfo = new PageInfo<>(users);
        // 返回Ajax 响应前端
        return new AjaxResult<>(pageInfo);
    }

    @RequestMapping("insert")
    public String insertJump(){
        return "user/insert";
    }

    @PostMapping("insertInfo")
    @ResponseBody
    public AjaxResult<Integer> insert(User user){
        Integer i = userService.insert(user);
        return new AjaxResult<>(i);
    }

    @DeleteMapping("delete/{id}")
    @ResponseBody
    public AjaxResult<Integer> delete(@PathVariable Integer id){
        Integer i = userService.delete(id);
        return new AjaxResult<>(i);
    }

    @RequestMapping("update")
    public String updateJump(User user, Model model){
        User user1 = userService.selectById(user);
        model.addAttribute("user1",user1);
        return "user/update";
    }

    @PostMapping("updateInfo")
    @ResponseBody
    public AjaxResult<Integer> updateInfo(User user){
        Integer i = userService.updateTo(user);
        return new AjaxResult<>(i);
    }

    @PostMapping("select/{name}")
    @ResponseBody
    public AjaxResult<PageInfo<User> > select(@PathVariable (value = "name", required = false) String name ,Integer page, Integer limit){
        PageHelper.startPage(page,limit);
        List<User>  users = userService.selectByName(name);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return new AjaxResult<>(pageInfo);
    }
}

